
/* globals svgEditor */
import { isValidUnit } from '../../common/units.js'
import imagePropertiesDialogHTML from './viewGraphic.html'
const template = document.createElement('template')
template.innerHTML = imagePropertiesDialogHTML
/**
 * @class SeImgPropDialog
 */
export class SeViewsGraphic extends HTMLElement {
  /**
    * @function constructor
    */
  constructor() {
    super()
    // create the shadowDom and insert the template
    this._shadowRoot = this.attachShadow({ mode: 'open' })

    this._shadowRoot.append(template.content.cloneNode(true))
    this.$dialog = this._shadowRoot.querySelector('#svg_createment')
    this.$cancelBtn = this._shadowRoot.querySelector('.tool_prefs_cancel')
    this.$delBtn = this._shadowRoot.querySelector('.tool_prefs_del')
    this.$changeContent = this._shadowRoot.querySelector('.changeContent')
    this.$content = this._shadowRoot.querySelector('.content')
    this.$detailContent =   this._shadowRoot.querySelector('.content div')
    this.$editorObj = null;


  }

  /**
   * @function init
   * @param {any} name
   * @returns {void}
   */
  init(i18next) {


  }

  /**
   * @function observedAttributes
   * @returns {any} observed
   */
  static get observedAttributes() {
    return ['dialog', 'common-ok', 'common-cancel','time-change']
  }

  /**
   * @function attributeChangedCallback
   * @param {string} name
   * @param {string} oldValue
   * @param {string} newValue
   * @returns {void}
   */
  async attributeChangedCallback(name, oldValue, newValue) {
    if (oldValue === newValue) return
    switch (name) {
      case 'dialog':
        if (newValue === 'open') {
          this.$dialog.open()
          await this.updateLib()
          await this.ViewContentUpdate();
          break
        } else {
          this.$dialog.close()
          break
        }
        break
      case 'common-cancel':
        this.$cancelBtn.textContent = newValue
        break
      case 'time-change':
        this.$editorObj= newValue
        break
      default:
        super.attributeChangedCallback(name, oldValue, newValue)
        break
    }
  }

 async getImgurl(){
  
  try{
    const response = await fetch(window.serviceUrl + "/svg/graphics/config");
    const json = await response.json();
    const curConfig = JSON.parse(json.data) || {}
    if(curConfig && curConfig?.bkgd_url){
        return curConfig?.bkgd_url;
    }else{
        return ''
    }

  }catch(error){
    console.log(error)
    return '';

  }

 

 }
 async parserXml (xml) {
    if (window.DOMParser) {
      var parser = new DOMParser();
      return parser.parseFromString(xml, 'text/xml');
    } else {
      xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
      var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
      xmlDoc.async = 'false';
      xmlDoc.loadXML(xml);
      return xmlDoc;
    }
  }


  async ViewContentUpdate() {
    const [x, y] = svgEditor.configObj.curConfig.dimensions
    var that = this;

    $(this._shadowRoot).find('.content').find('div>div>img').off('click').on('click',async function(e) {
      e.stopPropagation()
      e.preventDefault()
      $(this).addClass('press').siblings().removeClass('press')
      var imgSrc= $(this).attr('data-set');
      let primitiveType = $(this).data('key');
      let primitiveDesc = $(this).data('title');
      var reallyimgSrc = decodeURIComponent(escape(atob(imgSrc)))
      svgEditor.svgCanvas.clear()
      const $imgDialog = svgEditor.svgCanvas.$id('se-viewgrahic')
      $imgDialog.setAttribute('dialog', 'close')
      svgEditor.storage.setItem('svg-edit-graphicType', primitiveType)
      svgEditor.storage.setItem('svg-edit-graphicDesc', primitiveDesc)
      // var svgstr = reallyimgSrc.substring(reallyimgSrc.indexOf("bgurl="),reallyimgSrc.indexOf(">"))
      svgEditor.descTitle = primitiveDesc
      console.log('svgEditor',svgEditor)
      var svgstr  = await that.getImgurl();
      var bgColor = svgEditor.configObj.pref('bkgd_color')
      svgEditor.setBackground(bgColor,svgstr)
      await svgEditor.loadSvgString(reallyimgSrc)
      svgEditor.svgCanvas.setResolution(x, y)
      svgEditor.updateCanvas()
      svgEditor.layersPanel.populateLayers()
      svgEditor.svgCanvas.undoMgr.resetUndoStack()
      window.localStorage.setItem('svgedit-pictool', reallyimgSrc)
      // window.parent.currentSvgId=primitiveType + "/" + primitiveDesc
  })

  }
  /**
   * @function get
   * @returns {any}
   */


  /**
   * @function get
   * @returns {any}
   */


  async updateLib () {
    try {
      const response1 = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/sys/dict/item/262`)
      const  data1 = (await response1.json()).data;
      const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/graphics/list`)
      const  data = (await response.json()).data;
      var mapobj={}
      for(let i in data1){
        mapobj[data1[i]['dict_value']   ] =  data1[i]['dict_label']
      }
      var obj={}
      for(let i =0;i<data1.length;i++){
        var key = data1[i]['dict_value'] ;
        obj[key] =[]
      }
      var merageData ={...obj,...data};




      let changeTemplate = '';

      $(this._shadowRoot).find('.content').empty();
      var index=-1;

      for(var j in merageData){
        index++;
        var key =j;
        var value = merageData[j];
        var changeContent = '';
        var divItem;
        if(index>=1){
          divItem = $('<div></div>')
          changeTemplate +=  `<div>${mapobj[key]}</div>`
        }else{
          divItem =$(`<div class='active'></div>`)
          changeTemplate +=  `<div class='active'>${mapobj[key]}</div>`
        }

       if(value && !value.length){
        changeContent+= `<div></div> `
        divItem.append($(changeContent))
        $(this._shadowRoot).find('.content').append(divItem)

       }else{
        for(let k=0;k<value.length;k++){
          var gs=value[k];
          divItem.empty();
          let title = gs.title;
          let content = gs.content;
          if (!title) {
            continue; //跳出循环
          }

          let echart_64 = encodeURIComponent(escape(btoa("echart")))
          if(content.indexOf(echart_64)>-1){
            var ctx = decodeURIComponent(escape(atob(content)))
            var ctx_elem = $(ctx)
            ctx_elem.attr("width",280).attr("height",280)
              changeContent+= `<div><img title="${title}" style="opacity:0;z-index:9999;height:0px" data-key="${key}" data-title="${title}" data-set="${content}" src=""/><span style="top:0px" onclick="this.previousSibling.click()">${ctx_elem[0].outerHTML}</span><span><input class="ckinput" type=checkbox name="delKeys" data-key="${key}" data-title="${title}" />${title}</span> </div>`
              divItem.append($(changeContent))
              $(this._shadowRoot).find('.content').append(divItem)

          }else{
            changeContent+= `<div><img title="${title}" data-key="${key}" data-title="${title}" data-set="${content}" src="data:image/svg+xml;base64,${content}"><span><input class="ckinput" type=checkbox name="delKeys" data-key="${key}" data-title="${title}" />${title}</span></div>`
            divItem.append($(changeContent))
            $(this._shadowRoot).find('.content').append(divItem)

          }

        }

       }

      }
      this.$changeContent.innerHTML = changeTemplate;
    } catch (error) {
      console.error(`could not read file:`, error)
    }
  }




  get dialog() {
    return this.getAttribute('dialog')
  }

  /**
   * @function set
   * @returns {void}
   */
  set dialog(value) {
    this.setAttribute('dialog', value)
  }

  /**
   * @function connectedCallback
   * @returns {void}
   */
  connectedCallback() {
    const onCancelHandler = () => {
      const closeEvent = new CustomEvent('change', {
        detail: {
          dialog: 'closed'
        }
      })
      this.dispatchEvent(closeEvent)
    }

    const onDelHandler= async () => {
      const params = [];
      var cks = $(this._shadowRoot).find('.ckinput:checked')

      Array.from(cks).forEach(elem => {
        const key = $(elem).data('key');
        const title = $(elem).data('title');
        params.push({type:key, name: title})
      })

      const ok = await seConfirm(svgEditor.i18next.t('notification.removePrimitive'))
      const success = svgEditor.i18next.t('notification.removeSuccess')
      const fail = svgEditor.i18next.t('notification.removeFailed')
      if (ok == 'Ok') {


        const response = await fetch(`${svgEditor.configObj.curConfig.serviceUrl}/svg/graphics`, {
          method: 'DELETE',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify(params)
        });
        const json = await response.json()
        const message = svgEditor.i18next.t(json.code === '100000' ? success : fail)
        await seAlert(message)
        await this.updateLib()
      }

    }

    svgEditor.$click(this.$cancelBtn, onCancelHandler)

    svgEditor.$click(this.$delBtn, onDelHandler)


    const {svgCanvas} = svgEditor
    // this.$changeContent = this._shadowRoot.querySelector('.changeContent')
    this.ViewContentUpdate();

    var a = $(this._shadowRoot);
    $(this._shadowRoot).find('.changeContent').on('click','div',function(){
        $(this).addClass('active').siblings().removeClass("active")
        a.find('.content>div').eq($(this).index()).addClass('active').siblings().removeClass('active')

    })
  }

  }


// Register
customElements.define('se-viewgrahic-dialog', SeViewsGraphic)
